import {
    BackHandler,
    FlatList,
    Keyboard,
    TouchableWithoutFeedback,
    Animated,
    ActivityIndicator,
    View,
    Text, Platform,
} from "react-native";
import React, {
    useEffect,
    useRef,
    useState,
    useCallback,
    createContext,
    Dispatch,
    useMemo,
} from "react";
import styles from "./index.style";
import MessageItemActions from "../ChatDetail/MessageItemActions";
import {KeyboardAvoidingView} from "react-native-keyboard-controller";
import {useTheme} from "@/contexts/ThemeContext";
import {SessionType} from "@/types/chat-session";
import {ChatMessage, ChatMessageOrTimeLine} from "@/types/chat-message";
import MessageItem from "@/components/Chat/ChatDetail/MessageItem";
import BottomBar from "@/components/Chat/ChatDetail/BottomBar";
import QuoteButton from "@/components/Chat/ChatDetail/QuoteButton";
import {
    useChatMessageActions,
    useChatMessageState,
} from "@/hooks/chat/chat-message";
import {useChatSessionActions} from "@/hooks/chat/chat-session";
import {useChatDetailPageActions} from "@/hooks/chat/chat-detail-page";
import TimeLine from "@/components/Chat/ChatDetail/TimeLine";
import {groupMessagesWithTimeLine} from "@/utils/time-utils";

/// 抽屉类型
export type DrawerType = "keyboard" | "emoji" | "media" | null;

// 上下文属性
export interface ChatDetailContextProps {
    sessionId: string;
    sessionType: SessionType;
    sessionName: string;
    sessionAvatar: string;
    flatListRef: React.RefObject<any>;
    setShowDrawerType: Dispatch<React.SetStateAction<DrawerType>>;
    showDrawerType: DrawerType;
    inputText: string;
    setInputText: Dispatch<React.SetStateAction<string>>;
}

// 创建聊天详细页上下文
export const ChatDetailContext = createContext<ChatDetailContextProps>(
    {} as ChatDetailContextProps
);

/**
 * @author FlanChan
 * 聊天详细页组件
 */
export default function ChatDetail() {
    const {colors} = useTheme();
    const flatListRef = React.useRef<FlatList>(null);
    const loadingRef = useRef(false);
    const [inputText, setInputText] = useState("");
    const [showDrawerType, setShowDrawerType] = useState<DrawerType>("keyboard");
    const {groupedMessages, enableMultipleSelect, session} = useChatMessageState();
    const {
        clearMessages,
        getMessages,
        setEnableMultipleSelect,
        setReceiverTyping,
        setReply,
    } = useChatMessageActions();
    const {updateSession} = useChatSessionActions();
    const {resetCurrentChatDetailState} = useChatDetailPageActions();

    // 键盘弹出偏移量
    const translateY = useRef(new Animated.Value(0)).current;

    // 是否即将滚动到顶部
    const isCloseToTop = ({contentOffset}) => {
        const paddingToTop = 50; // 提前 50px 触发
        return contentOffset.y <= paddingToTop;
    };

    const handleBackPress = () => {
        if (enableMultipleSelect) {
            setEnableMultipleSelect(false); // 退出多选模式
            return true;
        }
        // 允许正常返回行为
        return false;
    };

    // 渲染消息列表项
    const renderMessageItem = useCallback(
        ({item}: { item: ChatMessageOrTimeLine; }) => {
            if (item.type === "timeline") {
                return <TimeLine timestamp={item.timestamp}/>
            } else {
                return <MessageItem item={item.data}/>
            }
        },
        []
    );

    const initMessages = async () => {
        console.log(session.sessionId, "初始化会话消息");
        await getMessages(session.sessionId)
        setTimeout(() => {
            flatListRef.current?.scrollToEnd({animated: false});
        }, 300); // 延迟一点避免渲染未完成
    }

    // 当进入页面时进行
    useEffect(() => {
        initMessages()

        // 设置当前会话的草稿
        if (session.draft) {
            setInputText(session.draft);
        }

        // 清除当前会话的未读数
        if (session.unreadCount > 0) {
            updateSession({
                sessionId: session.sessionId,
                unreadCount: 0,
            });
        }

        const showSub = Keyboard.addListener("keyboardDidShow", (e) => {
            Animated.timing(translateY, {
                toValue: -e.endCoordinates.height,
                duration: 100,
                useNativeDriver: true,
            }).start();
        });

        const hideSub = Keyboard.addListener("keyboardDidHide", (e) => {
            Animated.timing(translateY, {
                toValue: 0,
                duration: 100,
                useNativeDriver: true,
            }).start();
        });

        // 组件卸载/参数变化时清理定时器
        return () => {
            // 删除键盘监听事件
            showSub.remove();
            hideSub.remove();
            clearMessages();
            resetCurrentChatDetailState();
        };
    }, [session]); // 添加session作为依赖项


    // 监听退格键
    useEffect(() => {
        const backHandler = BackHandler.addEventListener(
            "hardwareBackPress",
            handleBackPress
        );

        return () => backHandler.remove();
    }, [enableMultipleSelect]);

    // 使用useMemo创建context值，避免不必要的重渲染
    const contextValue = useMemo(() => {
        // 如果session为null，提供默认值
        if (!session) {
            return {
                sessionId: "",
                sessionType: 0 as SessionType,
                sessionName: "",
                sessionAvatar: "",
                flatListRef,
                setShowDrawerType,
                showDrawerType,
                inputText,
                setInputText,
            };
        }

        return {
            sessionId: session.sessionId,
            sessionType: session.sessionType,
            sessionName: session.sessionName,
            sessionAvatar: session.sessionAvatar,
            flatListRef,
            setShowDrawerType,
            showDrawerType,
            inputText,
            setInputText,
        };
    }, [session, showDrawerType, inputText]);

    // 渲染加载状态或聊天界面
    if (!session) {
        return (
            <View
                style={[
                    styles.container,
                    {
                        backgroundColor: colors.backgroundLight,
                        justifyContent: "center",
                        alignItems: "center",
                    },
                ]}
            >
                <ActivityIndicator size="large" color={colors.primary}/>
                <Text style={{marginTop: 10, color: colors.text.primary}}>
                    加载会话中...
                </Text>
            </View>
        );
    }

    // 正常渲染聊天界面
    return (
        <TouchableWithoutFeedback onPress={() => setShowDrawerType(null)}>
            <KeyboardAvoidingView
                style={[styles.container, {backgroundColor: colors.backgroundLight}]}
            >
                    <FlatList
                        style={{flex: 1}}
                        windowSize={5}
                        maxToRenderPerBatch={5}
                        removeClippedSubviews={!enableMultipleSelect}
                        maintainVisibleContentPosition={{
                            minIndexForVisible: 0,
                        }}
                        ref={flatListRef}
                        data={groupedMessages}
                        onScroll={async (event) => {
                            if (loadingRef.current) {
                                return;
                            }
                            if (isCloseToTop(event.nativeEvent)) {
                                loadingRef.current = true;
                                try {
                                    await getMessages(session.sessionId);
                                } finally {
                                    loadingRef.current = false;
                                }
                            }
                        }}
                        keyExtractor={(item: ChatMessage<any, any>) =>
                            item.messageId
                                ? String(item.messageId)
                                : `temp-${item.createTime}-${Math.random()}`
                        }
                        renderItem={renderMessageItem}
                    />
                <ChatDetailContext.Provider value={contextValue}>
                    {/* 消息操作底栏 */}
                    <MessageItemActions/>
                    {/* 引用消息显示 */}
                    <QuoteButton/>
                    {/* 根据模式显示底部组件 */}
                    {!enableMultipleSelect ? (
                        <Animated.View style={{transform: [{translateY}]}}>
                            <BottomBar/>
                        </Animated.View>
                    ) : null}
                </ChatDetailContext.Provider>
            </KeyboardAvoidingView>
        </TouchableWithoutFeedback>
    );
}
